import vue from 'vue'
import vueRouter from 'vue-router'

import store from '@/store'

vue.use(vueRouter)

import routes from '@/router/routes'

// 创建路由
let router = new vueRouter({
    routes,
    mode: 'history',
})

// console.log(store);
// 全局路由守卫

// 判断登录是否过时，一天
let time = 24 * 60 * 60 * 1000

router.beforeEach((to, from, next)=>{
    let token = JSON.parse(localStorage.getItem('token'))
    // console.log(token)
    // 如果用户访问需要登录的路由，并且没有登录，则查找本地是否有token
    if (to.meta.requiresAuth && !store.state.isLogin) {
        if(token){
            // 验证本地存储的token是否过期
            let deltime = new Date().getTime()
            if(deltime - token.time > time){
                alert('登录已经过期，请重新登录')
                localStorage.clear()
                next({
                    path: '/user/login',
                    query: { redirect: to.fullPath }
                })
                setTimeout(console.clear(), 200)
            }else{
                // console.log("成功验证token")
                next()
            }
        }else{
            next({
                path: '/user/login',
                query: { redirect: to.fullPath }
            })
            setTimeout(console.clear(), 200)
        }
    } else {
        next()
    }
    // next(false)
})


// 导出路由
export default router